package com.carful.wx.service.impl;

import com.carful.wx.config.WxH5Config;
import com.carful.wx.service.WxH5Service;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

/**
 * @author ad
 * Date 2024/5/24 9:51
 */

@Transactional
@Slf4j
@Service
public class WxH5ServiceImpl implements WxH5Service {

    @Value("${spring.profiles.active:dev}")
    private String active;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private WxH5Config wxH5Config;

    /**
     * 应用令牌
     */
    private String token;
    /**
     * 上次获取token时间
     */
    private volatile long lastTime = 0L;

    /**
     * 失效时间秒 (官方文档是 7200秒)
     */
    @Value("${ding.failureTime:7000}")
    private long failureTime;

    @Getter
    public static class ACCESS_TOKEN {
        private String access_token;
        private Integer expires_in;
        private String openid;
        private String scope;
        private Integer is_snapshotuser;
        private String unionid;
/**
 *                 "access_token":"ACCESS_TOKEN",
 *                 "expires_in":7200,
 *                 "refresh_token":"REFRESH_TOKEN",
 *                 "openid":"OPENID",
 *                 "scope":"SCOPE",
 *                 "is_snapshotuser": 1,
 *                 "unionid": "UNIONID"
 */
    }

    @Override
    public String getLoginUrl(String state) {

        String oauth2Url = wxH5Config.getOauth2_url();
        oauth2Url.replace("{appid}", wxH5Config.getAppid());
        oauth2Url.replace("{redirect_uri}", wxH5Config.getRedirect_uri());
        oauth2Url.replace("{scope}", wxH5Config.getScope());
        if (state != null) oauth2Url.replace("{state}", state);

        return oauth2Url;
    }

    @Override
    public String openid(String code, String state) {
        String appid = wxH5Config.getAppid();
        String secret = wxH5Config.getSecret();
        ACCESS_TOKEN accessToken = restTemplate.getForObject(wxH5Config.getAccess_token_url(), ACCESS_TOKEN.class, appid, secret, code);
        String openid = accessToken.getOpenid();

        return openid;
    }
}
